import { ref, onMounted, onUnmounted } from "vue";

interface Options {
  immediate?: boolean;
}
function useInterval(
  fn: () => void,
  delay: number | null | undefined,
  options?: Options
): void {
  const immediate = options?.immediate;

  const fnRef = ref<() => void>();
  fnRef.value = fn;
  let timer: number;

  onMounted(() => {
    if (delay === null || delay === undefined) return;
    if (immediate) {
      fnRef.value?.();
    }
    timer = setInterval(() => {
      fnRef.value?.();
    }, delay);
  });

  onUnmounted(() => {
    clearInterval(timer);
  });
}

export default useInterval;
